import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import { arrayLike } from '../utils/arrayUtils';

class THeaderCell extends React.Component {
	constructor() {
		super();
		this.state = {};
	}

	onClick = (...args) => {
		const { sortPath, onClick } = this.props;

		if (onClick) onClick(...args);
		if (!sortPath) return;

		this.context.doSort(sortPath);
	};

	render() {
		const { sortPath, className, ...props } = this.props;
		const { sortPath: cSortPath, sortASC: cSortASC } = this.context;
		const isSorting = arrayLike(sortPath, cSortPath);

		return (
			<th
				{...props}
				role="button" onClick={this.onClick}
				className={classNames(className, {
					sortable: sortPath,
					up: isSorting && cSortASC,
					down: isSorting && !cSortASC,
				})}
			/>
		);
	}
}

THeaderCell.propTypes = {
	children: PropTypes.node,
	className: PropTypes.string,
	onClick: PropTypes.func,
	sortPath: PropTypes.oneOfType([PropTypes.array, PropTypes.string]),
};

THeaderCell.contextTypes = {
	sortPath: PropTypes.oneOfType([PropTypes.array, PropTypes.string]),
	sortASC: PropTypes.bool,
	doSort: PropTypes.func,
};

export default THeaderCell;
